package mysql

import (
	"pharymacy-management-system/models"
)

func SelectAllDrugType() (typeList []models.DrugType, err error) {
	// 执行查询语句
	err = db.Select(&typeList, "SELECT * FROM w_type")
	return typeList, err
}

func SelectDrugTypeById(id int) (*models.DrugType, error) {
	var count int
	err := db.Get(&count, `SELECT COUNT(*) FROM w_type WHERE type_id = ?`, id)
	if err != nil {
		return nil, err
	}
	if count == 0 {
		return nil, nil
	}
	var drugType models.DrugType
	err = db.Get(&drugType, `SELECT type_id,type_name FROM w_type WHERE type_id = ?`, id)
	return &drugType, err
}

func SelectDrugTypeByName(typeName string) (*models.DrugType, error) {
	var count int
	err := db.Get(&count, `SELECT COUNT(*) FROM w_type WHERE type_name = ?`, typeName)
	if err != nil {
		return nil, err
	}
	if count == 0 {
		return nil, nil
	}
	var drugType models.DrugType
	err = db.Get(&drugType, `SELECT * FROM w_type WHERE type_name = '?'`, typeName)
	return &drugType, err
}

func InsertDrugType(typeName string) (err error) {
	// 执行插入语句
	_, err = db.Exec(`INSERT INTO w_type (type_name) VALUES (?)`, typeName)
	return err
}

func UpdateDrugTypeById(p models.ParamType) (err error) {
	// 执行更新语句
	_, err = db.Exec(`UPDATE w_type SET type_name = ? WHERE type_id = ?`, p.NewTypeName, p.TypeID)
	return err
}

func SelectAllDrug() (drugList []models.Drug, err error) {
	sqlStr := `select w_drug.drug_id,w_drug.drug_name,w_drug.drug_specs,w_drug.drug_price,w_type.type_name from	w_type,w_drug_type,w_drug where w_drug.drug_id=w_drug_type.drug_id and w_type.type_id=w_drug_type.type_id`
	err = db.Select(&drugList, sqlStr)
	return drugList, err
}

func SelectDrugById(id int) (drug *models.Drug, err error) {
	err = db.Get(&drug, "SELECT * FROM w_drug WHERE drug_id = ?", id)
	return drug, err
}

func InsertDrug(drug *models.Drug, drugType *models.DrugAndType) (err error) {
	// 开启事务
	tx, err := db.Beginx()
	if err != nil {
		return
	}
	// 执行插入语句
	sqlStr := `insert into w_drug(drug_id, drug_name, drug_specs, drug_price) VALUE (?,?,?,?)`
	sqlStr2 := `insert into w_drug_type(type_id,drug_id) value (?,?)`
	tx.MustExec(sqlStr, drug.DrugID, drug.DrugName, drug.DrugSpecs, drug.DrugPrice)
	tx.MustExec(sqlStr2, drugType.TypeID, drugType.DrugID)
	return tx.Commit()
}

func UpdateDrugById(drug *models.Drug, drugType *models.DrugAndType) (err error) {
	// 开启事务
	tx, err := db.Beginx()
	if err != nil {
		return
	}
	// 执行更新语句
	sqlStr := `update w_drug set drug_name=?,drug_specs=?,drug_price=? where drug_id=?`
	sqlStr2 := `update w_drug_type set type_id=? where drug_id=?`
	tx.MustExec(sqlStr, drug.DrugName, drug.DrugSpecs, drug.DrugPrice, drug.DrugID)
	tx.MustExec(sqlStr2, drugType.TypeID, drugType.DrugID)
	return tx.Commit()
}
